import socket
import re


index_content = '''
HTTP/1.x 200 ok
Content-Type: text/html

'''

file = open('index.html', 'rb')
index_content += file.read().decode('utf-8')
file.close()


reg_content = '''
HTTP/1.x 200 ok
Content-Type: text/html

'''

file = open('reg.html', 'rb')
reg_content += file.read().decode('utf-8')
file.close()



socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind(('127.0.0.1', 80))
socket.listen(5)

while True:

    connection, address = socket.accept()
    request = connection.recv(1024)
    method = request.decode().split(' ')[0]
    src = request.decode().split(' ')[1]
    # print('method:',method)
    # print('src:',src)

    if method == 'GET':
        if src == '/index.html':
            content = index_content
        elif src == '/reg.html':
            content = reg_content
        elif re.match('^/\?.*$', src):
            entry = src.split('?')[1]
            content = 'HTTP/1.x 200 ok\r\nContent-Type: text/html\r\n\r\n'
            content += entry

        else:
            continue
    elif method == 'POST':
        form = request.decode().split('\r\n')
        entry = form[-1]
        content = 'HTTP/1.x 200 ok\r\nContent-Type: text/html\r\n\r\n'
        content += entry
    else:
        continue
    connection.sendall(content.encode())
    connection.close()